﻿using Microsoft.Win32;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace LD
{
    public class HttpClientHelper
    {
         //Machinedata: urL:http://10.0.0.2:5008/v5/capture/machinedata
        //ERRORDATA:     http://10.0.0.2:5008/v5/capture/errordata
        //MACHINESTATE:  http://10.0.0.2:5008/v5/capture/machinestate

        public string HttpRecieve = "";

        public string PostMoths(string url, string hivedata)
        {
            string StrDate = "";
            string strValue = "";
            string paraUrlCoded="";
            try
            {
                string strURL = url;//+param;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                request.Proxy = null;
                request.ServicePoint.Expect100Continue = false;
                paraUrlCoded = hivedata;
                byte[] byteWrite;
                byteWrite = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = byteWrite.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(byteWrite, 0, byteWrite.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
             
                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate;
                }
                
            }
            catch (Exception ex)
            {
                strValue = "Error:"+ex.Message.ToString();
            }
            return strValue;
        }

        public string[] GetFilepathsFromhivedata(string hivedata)
        {
            string blobsdata = hivedata.Substring(hivedata.IndexOf("\"blobs\":"));
            string[] files = blobsdata.Replace("\"blobs\":[", "").Replace("]", "").Replace("\"", "").Replace("{", "").Replace("}", "").Split(',');
            string[] filepaths = new string[files.Length];
            for (int i = 0; i < filepaths.Length;i++ )
            {
                filepaths[i] = files[i].Replace("file_name:","");
            }
            return filepaths;
        }

        //public string[] GetNewHivedata(string hivedata)
        //{
        //    string blobsdata = hivedata.Remove(hivedata.IndexOf("\"blobs\":"));
        //}
        /// <summary>
        /// 通过multipart/form-data模式 向网页post数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="hivedata"></param>
        /// <returns></returns>
        public string PostMoths_form(string url, string hivedata)
        {
            string StrDate = "";
            string strValue = "";
     
            try
            {
                string strURL = url;//+param;"http://httpbin.org/post"
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                request.Timeout = 4000;
                //request.Timeout = GVar.hiveUpTimeOut;
                var memStream = new MemoryStream(); 
                // 边界符  
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                // 边界符  
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                // 最后的结束符  
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
                request.Method = "POST";
                request.ContentType = "multipart/form-data;boundary=" + boundary;//multipart/form-data模式
                string[] filePaths = GetFilepathsFromhivedata(hivedata);
                string newdata = hivedata;
                if (filePaths.Length > 0)
                {
                    newdata = hivedata.Remove(hivedata.IndexOf("\"blobs\":"));
                    newdata += "\"blobs\":[";
                    for (int i = 0; i < filePaths.Length;i++ )
                    {
                        if (string.IsNullOrEmpty(filePaths[i]))
                        {
                            continue;
                        }
                        if (!System.IO.File.Exists(filePaths[i]))
                        {
                            //MessageBox.Show("上传失败<>:" + filePaths[i] + "不存在！");
                            //Log.WriteLine("上传失败<>:" + filePaths[i] + "不存在！");
                            continue;
                        }
                        var fileStream = new FileStream(filePaths[i], FileMode.Open, FileAccess.Read);
                        // 写入文件  
                        const string filePartHeader =
                            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                             "Content-Type: {2}\r\n\r\n";
                        var header = string.Format(filePartHeader, "file"+(i+1), filePaths[i], GetMimeMapping(filePaths[i]));
                        var headerbytes = Encoding.UTF8.GetBytes(header);

                        memStream.Write(beginBoundary, 0, beginBoundary.Length);
                        memStream.Write(headerbytes, 0, headerbytes.Length);
                        byte[] buffer = new byte[4096];
                        int bytesRead = 0;
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)//将文件内容写入流
                        {
                            memStream.Write(buffer, 0, bytesRead);
                        }
                        fileStream.Close();
                        var enterbytes = Encoding.UTF8.GetBytes("\r\n");
                        memStream.Write(enterbytes, 0, enterbytes.Length);
                        newdata += "{\"file_name\":\"" + Path.GetFileName(filePaths[i]) + "\"},";
                    }
                    newdata = newdata.TrimEnd(',');//Substring(0, newdata.Length - 1);
                    newdata += "]}";
                }

                memStream.Write(beginBoundary, 0, beginBoundary.Length);

                var databytes = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\""+"\r\n\r\n{1}\r\n","jsondata",newdata));

                //Comvaria.tabelname = newdata;
                memStream.Write(databytes, 0, databytes.Length);
                memStream.Write(endBoundary, 0, endBoundary.Length);

                request.ContentLength = memStream.Length;
                request.Proxy = null;
                request.ServicePoint.Expect100Continue = false;
                Stream writer = request.GetRequestStream();

                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();

                //paraUrlCoded = hivedata;
                //byte[] byteWrite;
                //byteWrite = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                writer.Write(tempBuffer, 0, tempBuffer.Length);
                writer.Close();
                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();

                StreamReader Reader = new StreamReader(s, Encoding.UTF8);
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate;
                }
            }
            catch (Exception ex)
            {
                strValue = "Error:" + ex.Message.ToString();
            }
            return strValue;
        }


        public static string GetMimeMapping(string fileName)
        {
            string mimeType = "application/octet-stream";
            string ext = Path.GetExtension(fileName).ToLower();
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
            {
                mimeType = regKey.GetValue("Content Type").ToString();
            }
            return mimeType;
        }


        public string HttpClientTest(string url)
        {
            string strValue = "";
            try
            {
                string strURL = url;//+param;
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                strValue = "OK";
            }
            catch (Exception ex)
            {
                strValue = "Error:" + ex.Message.ToString();
            }
            return strValue;
        }
    }
}